import json
import pandas as pd
import datetime
import pytest
import sys



'''
python处理json的示例。
其中step1和step3根据数据交互的方式进行调整。
'''

# step1->读取json中的数据
# with open('json_sample.txt','r',encoding='utf8') as f:
#     read_data=f.read()
#     json_data =json.loads(read_data)
#     print(json_data)
def func(data):
    # step2->处理数据
    # ---将json数组转化为dataframe
    df_json=pd.json_normalize(data,record_path=['data','result'])
    # ---取近12个自然月
    date_now = datetime.date.today()
    date_lastmth=date_now.replace(day=1) + datetime.timedelta(days=-1)
    date_lastyear=datetime.date(date_now.year-1,date_now.month,1)
    str_lastmth=date_lastmth.strftime("%Y%m")
    str_lastyear=date_lastyear.strftime("%Y%m")
    # ---筛选dataframe中符合条件的数据
    df_tmp=df_json[(df_json['sign']=='销项') & (df_json['zfbz']==False)
                & (df_json['ssyf']>=str_lastyear) & (df_json['ssyf']<=str_lastmth)]
    # ---对数据进行排序
    df_tmp.loc[:,'kprq']=pd.to_datetime(df_tmp['kprq'])
    df_tmp=df_tmp.sort_values(['kprq'],ascending=True)
    # ---向前取上一次开票日期
    df_tmp['last_kprq']=df_tmp['kprq'].shift()
    # ---加工时间间隔
    df_tmp['gap_days']=df_tmp['kprq']-df_tmp['last_kprq']

    # step3->输出结果
    print(df_tmp['gap_days'].max().days)


if __name__ == '__main__':
    # s = '{"name":"张三","age":18}'
    # print(type(s))
    # result = json.loads(s)
    # print(result)

    jsonStr = sys.argv[1]
    result = json.loads(jsonStr)
    # print("data2['name']: ", result['name'])
    # print("data2['age']: ", result['age'])
    # print(10/0)
    print(func(data=result))